//#include "CTexture.h"
#include "CGameEnv.h"


CTexture::CTexture()
{
    mFilename = 0;
    mTextureHandle = 0;

    isBlendingActive = false;
    //orthoHelper = new C2DHelpers;
}

CTexture::~CTexture()
{
    glDeleteTextures(1, &mTextureHandle);
    mTextureHandle = 0;
    delete[] mFilename;
    mFilename = 0;

    //delete orthoHelper;

}

// This code was borrowed from Sol's OpenGL basecode at sol.gfxile.net
GLuint CTexture::load_texture(char *aFilename, int clamp)
{
    // Check if texture already loaded
    if(mFilename != 0)
    if(stricmp(mFilename, aFilename) == 0 ) // No difference, perfect match
    {
        return mTextureHandle;
    }


    // Create OpenGL texture handle and bind it to use
    GLuint texName;
    glGenTextures(1,&texName);
    glBindTexture(GL_TEXTURE_2D, texName);

    loadTexture(aFilename, clamp); // The texture is loaded from disk and into glTexImage2D. Magic! No pointers or anything exchanged. OpenGL has it.

    mFilename = strdup(aFilename); // duplicate aFilename cstring. Gotta copy the chars you know! This ain't C++ strings or Java!
    mTextureHandle = texName;
    mClamp = clamp;

    return mTextureHandle;
}

// Draw a sprite... this should be in a general 2D drawing class.
void CTexture::drawSprite(int tex, float x, float y, float w, float h, float alpha)
{
    orthoHelper.BeginOrtho();
    glBindTexture(GL_TEXTURE_2D, tex);
    glEnable(GL_TEXTURE_2D);

    if(isBlendingActive)
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    }

    glColor4f(1.0f, 1.0f, 1.0f, alpha);
    glBegin(GL_TRIANGLE_STRIP);
        glTexCoord2f(0,0);
        glVertex2f(x - w / 2, y - h / 2);
        glTexCoord2f(0,1);
        glVertex2f(x - w / 2, y + h / 2);
        glTexCoord2f(1,0);
        glVertex2f(x + w / 2, y - h / 2);
        glTexCoord2f(1,1);
        glVertex2f(x + w / 2, y + h / 2);
    glEnd();
    orthoHelper.EndOrtho();
}

void CTexture::DrawSpriteNoState(int tex, float x, float y, float z, float w, float h, float alpha)
{
    glBindTexture(GL_TEXTURE_2D, tex);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    glColor4f(1.0f, 1.0f, 1.0f, alpha);
    glBegin(GL_TRIANGLE_STRIP);
        glTexCoord2f(0,0);
        glVertex3f(x - w / 2, y - h / 2, z);
        glTexCoord2f(0,1);
        glVertex3f(x - w / 2, y + h / 2, z);
        glTexCoord2f(1,0);
        glVertex3f(x + w / 2, y - h / 2, z);
        glTexCoord2f(1,1);
        glVertex3f(x + w / 2, y + h / 2, z);
    glEnd();
}

void CTexture::setBlending(bool activated)
{
    isBlendingActive = activated;
}

